import logging
import threading

from flask import request, Response, session, jsonify
from flask_restful import Resource

from utils.login_helper import check_user_state
from utils.sql_info import get_user_ks, save_user_ks, get_user_info, save_user_info, get_user_temp, get_user_id
from utils.sql_login import user_login
from utils.sql_user import registry_user, reset_user_password, get_user_lnh
from utils.str_util import gen_random_str


lock = threading.Lock()

class login_api(Resource):

    def post(self):
        form = request.form
        email = form.get("email")
        password = form.get("password")

        c = gen_random_str(30)

        with lock:
            login_code = user_login(email, password, c)

        if login_code == 0:
            session['email'] = email
            session['level'], session['name'], session['head'] = get_user_lnh(email)
            session['uid'] = get_user_id(email)

            response = Response()
            response.set_cookie('up', c, max_age=604800)
            response.set_cookie('email', email, max_age=604800)

            logging.info(f"用户{email}登录成功")

            return response

        return f'{login_code}'

class registry_api(Resource):

    def post(self):
        form = request.form
        email = form.get("email")
        icode = form.get("icode")

        if email is None or icode is None:
            return '-1'

        with lock:
            registry_code = registry_user(email, icode)

        return f'{registry_code}'

class get_user_ks_info_api(Resource):

    @check_user_state
    def post(self):
        email = session.get('email')
        # email = "3488636116@qq.com"

        with lock:
            data = get_user_ks(email)

        return jsonify(data)


class save_user_ks_info_api(Resource):

    @staticmethod
    def check_t(t: str):
        if len(t) != 5:
            return False
        if t[2] != ':':
            return False
        if t[0] != '0' and t[0] != '1' and t[0] != '2':
            return False
        a = t[1]
        b = t[3]
        c = t[4]
        try:
            int(a)
            int(b)
            int(c)
        except ValueError:
            return False
        return True

    @check_user_state
    def post(self):
        form = request.form
        ksname = form.get("ksname")
        kspassword = form.get("kspassword")
        botopen = form.get("botopen")
        emailopen = form.get("emailopen")
        email = session.get('email')

        # 获取上报时间
        try:
            t1 = form.get("t1")[0:-3]
            t2 = form.get("t2")[0:-3]
        except Exception as e:
            print(e)
            return jsonify(['0', '上报时间为非法参数'])

        # 兼容手机端
        if "上午" in t1:
            t1 = t1[2:]
            if len(t1) == 4:
                t1 = '0' + t1
        if "下午" in t2:
            t2 = t2[2:]
            if len(t2) == 4:
                _ = t2.split(':')
                ii = int(_[0])
                t2 = str(ii + 12) + ':' + _[1]

        if not (self.check_t(t1) and self.check_t(t2)):
            return jsonify(['0', '保存失败'])

        if not ksname or not kspassword or not botopen:
            return jsonify(['0', '非法请求'])

        logging.info(f"用户({email})保存科师信息请求，"
                     f"[ksname:{ksname}];[kspassword:{kspassword}];[botopen:{botopen}];"
                     f"[email:{email}];[t1:{t1}];[t2:{t2}];[emailopen:{emailopen}]")

        with lock:
            save_state = save_user_ks(ksname, kspassword, botopen, email, t1, t2, emailopen)

        if save_state:
            return jsonify(['1', '保存成功'])
        return jsonify(['0', '保存失败'])


class get_user_info_api(Resource):

    @check_user_state
    def post(self):
        email = session.get('email')
        # email = "3488636116@qq.com"
        with lock:
            data = get_user_info(email)

        return jsonify(data)


class save_user_info_api(Resource):

    @check_user_state
    def post(self):
        form = request.form
        uname = form.get("uname")
        password = form.get("password")
        email = session.get('email')
        # email = "3488636116@qq.com"

        if not uname or not password:
            return jsonify(['0', '非法请求'])

        with lock:
            save_state = save_user_info(uname, password, email)

        if save_state:
            return jsonify(['1', '保存成功'])
        return jsonify(['0', '保存失败'])

class reset_password_api(Resource):

    def post(self):
        form = request.form
        email = form.get('email')

        if not email:
            return "-1"

        with lock:
            return str(reset_user_password(email))


class get_user_temp_api(Resource):

    @check_user_state
    def post(self):
        uid = int(session['uid'])

        with lock:
            user_list = get_user_temp(uid)

        return jsonify(user_list)

